//
//  tababrController.swift
//  WeiboMini
//
//  Created by gaoliang on 15/11/17.
//  Copyright © 2015年 gaoliang. All rights reserved.
//

import UIKit

class tababrController: UITabBar {

    //默认的构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    // 如果重写 init(frame:) 系统会默认为这个控件是通过代码创建
    required init?(coder aDecoder: NSCoder) {
        //只有默认报错的语句
        //如果有调用者通过 xib/sb 创建了该对象 这个时候程序就会崩溃
        super.init(coder: aDecoder)
        setupUI()
    }
    private func setupUI() {
        //添加撰写按钮
        addSubview(composeBtn)
    }
    //MARK:addSubview时会调用这个方法(重排按钮)
    override func layoutSubviews() {
        super.layoutSubviews()
        //手动更改按钮的位置
        let w = self.bounds.width / 5
        let h = self.bounds.height
        let rect = CGRect(x: 0, y: 0, width: w, height: h)
        
        //定义自增变量
        var index: CGFloat = 0
        for subview in subviews {
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                // 修改 frame
                subview.frame = CGRectOffset(rect, index * w, 0)
                index += index == 1 ? 2 : 1
            }
        }
        // 设置撰写(+)按钮的位置
        composeBtn.frame = CGRectOffset(rect, w * 2, -20)
        bringSubviewToFront(composeBtn)
        
    }
    
    //MARK:懒加载控件
    lazy var composeBtn: UIButton = {
        //自定义样式的按钮
        let btn = UIButton()
        //设置按钮
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.sizeToFit()
        return btn
    }()
}
